package com.heima.kafka.sample;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.*;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-27 10:19
 */
public class KafkaStreamQuickStart106 {

    public static void main(String[] args) {

        Properties properties = new Properties();
        //kafka服务地址
        properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //key value序列化器
        properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        //stream流处理取个id
        properties.put(StreamsConfig.APPLICATION_ID_CONFIG,"stream-test-106-1");

        //三要素
        StreamsBuilder streamsBuilder = new StreamsBuilder();
        //第一要素，数据来源
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input"); //key null value : hello kafka
        //第二要素，数据处理器
        //to 第三要素，发送到topic中
        stream.flatMapValues((ValueMapper<String, Iterable<String>>) value -> {
            //"hello kafka" -> List<String> hello kafka
            return Arrays.asList(value.split(" "));
        }).groupBy((key, value) -> value) // kafka | kafka  itcast  hello | hello
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                .count() //key : kafka  value : 2
                .toStream()
                .map((KeyValueMapper<Windowed<String>, Long, KeyValue<String, String>>) (key, value)
                        -> new KeyValue<>(key.key(),value.toString()))
                .to("itcast-topic-out");

        KafkaStreams kafkaStreams = new KafkaStreams(streamsBuilder.build(),properties);

        //启动流式计算
        kafkaStreams.start();
    }
}
